<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>参数分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="注意: 只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false">
      </el-alert>
      <!-- 商品分类区域 -->
      <el-row class="goods_opt">
        <el-col>
          <span>选择商品分类 :</span>
          <el-cascader           
            :options="cateList"
            :props="cateProps"
            v-model="cateKeys"
            @change="cateIdChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tabs标签页区域 -->
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <el-tab-pane label="动态参数" name="many">
            <el-button 
              type="primary" 
              :disabled="isDisabled"
              size="mini"
              @click="paramsDialogVisible = true">添加参数
            </el-button>         
          <!-- 动态参数的表格 -->
          <el-table
            :data="manyTableData" 
            style="width: 100%"
            border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag 
                  v-for="(item,i) in scope.row.attr_vals" 
                  :key="i"
                  closable
                  @close="tagClose(scope.row,i)">{{item}}
                </el-tag>
                <!-- tag标签的input文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInput(scope.row)"
                  @blur="handleInput(scope.row)">
                </el-input>
                <el-button 
                  v-else 
                  class="button-new-tag" 
                  size="small" 
                  @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button 
                  type="primary" 
                  icon="el-icon-edit"
                  size="mini"
                  @click="editBtn(scope.row)">编辑
                </el-button>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteBtn(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button 
            type="primary"
            :disabled="isDisabled"
            size="mini"
            @click="paramsDialogVisible = true">添加属性
          </el-button>
          <!-- 静态属性的表格 -->
          <el-table
            :data="onlyTableData" 
            style="width: 100%"
            border stripe>
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag 
                  v-for="(item,i) in scope.row.attr_vals" 
                  :key="i"
                  closable
                  @close="tagClose(scope.row,i)">{{item}}
                </el-tag>
                <!-- tag标签的input文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInput(scope.row)"
                  @blur="handleInput(scope.row)">
                </el-input>
                <el-button 
                  v-else 
                  class="button-new-tag" 
                  size="small" 
                  @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button 
                  type="primary" 
                  icon="el-icon-edit"
                  size="mini"
                  @click="editBtn(scope.row)">编辑
                </el-button>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteBtn(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数/属性的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="paramsDialogVisible"
      width="45%"
      @close="paramsClose">
      <el-form :model="paramsForm" :rules="paramsRules" ref="paramsForm" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="paramsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="paramsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="paramsDialog">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="45%"
      @close="editClose">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name:'Params',
  data() {
    return {
      cateList:[],
      cateProps:{
        value:'cat_id',
        label:'cat_name',
        children:'children',
        expandTrigger: 'hover',
      },
      cateKeys:[],
      // 当前页面激活的页面标签的名称
      activeName:'many',
      // 动态参数数据
      manyTableData:[],
      // 静态属性数据
      onlyTableData:[],
      // 添加参数对话框的展示与隐藏
      paramsDialogVisible: false,
      // 表单的参数数据
      paramsForm:{},
      paramsRules:{
        attr_name:[
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
        ]
      },
      // 编辑对话框的展示与隐藏
      editDialogVisible: false,
      // 编辑对话框的表单数据
      editForm:{},
      editRules:{
        attr_name:[
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
        ]
      },
    }
  },
  computed:{
    isDisabled(){
      if(this.cateKeys.length === 3){
        return false
      }
      return true
    },
    // 级联选择器选中项的分类id
    cateId(){
      if(this.cateKeys.length === 3){
        return this.cateKeys[2]
      }
      return null
    },
    // 添加参数/静态属性对话框的文本
    titleText(){
      if(this.activeName === 'many'){
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  created(){
    this.getCateList()
  },
  methods:{
    // 获取商品分类
    async getCateList(){
      const {data:res} = await this.$http.get('categories')
      //console.log(res)
      if(res.meta.status !== 200) return this.$message.error('获取商品分类失败')
      this.cateList = res.data
    },

    // 级联选择器选择项变化时触发此函数
    cateIdChange(){
      this.getParamsData()     
    },
    // tabs标签页的变化时触发此函数
    tabClick(){
      //console.log(this.activeName)
      this.getParamsData()  
    },
    // 获取参数列表数据
    async getParamsData(){
      // 若cateKeys数组的长度不为3，说明没有选择第三级分类
      if(this.cateKeys.length !== 3){
        return this.cateKeys = []
      }
      // 选择第三级分类后发起参数列表的请求
      const {data:res} = await this.$http.get('categories/' + this.cateId + '/attributes',
      { params:{sel:this.activeName} })
      //console.log(res)
      if(res.meta.status !== 200) return this.$message.error('获取参数列表失败')
      // 将参数的字符串形式的可选项转换为数组形式，用v-for渲染
      res.data.forEach( item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 为每一个参数设置单独的文本框内容,显示隐藏
        item.inputVisible = false
        item.inputValue = ''
      })
      if(this.activeName === 'many'){
        this.manyTableData = res.data 
      } else {
        this.onlyTableData = res.data
      }     
    },
    // 添加参数对话框的确定按钮
    paramsDialog(){
      this.$refs.paramsForm.validate( async value => {
        if(!value) return 
        const {data:res} = await this.$http.post('categories/' + this.cateId+ '/attributes',
        {attr_name: this.paramsForm.attr_name, 
         attr_sel:this.activeName})
        //console.log(res)
        if(res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加参数成功')
        this.getParamsData()
        this.paramsDialogVisible = false
      })    
    },
    // 添加参数对话框的关闭事件
    paramsClose(){
      this.$refs.paramsForm.resetFields()
      this.paramsDialogVisible = false
    },
    // 编辑按钮,展示编辑对话框
    async editBtn(params){
      const {data:res} = await this.$http.get('categories/' + this.cateId + '/attributes/' + params.attr_id,
      { params:{attr_sel: this.activeName}
      })
      //console.log(res)
      if(res.meta.status !== 200) return this.$message.error('编辑失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 编辑对话框的确定按钮
    editDialog(){
      this.$refs.editForm.validate( async value => {
        if(!value) return 
        const {data:res} = await this.$http.put('categories/' + this.cateId +'/attributes/' + this.editForm.attr_id,
        {attr_name: this.editForm.attr_name,
         attr_sel: this.activeName})
        if(res.meta.status !== 200) return this.$message.error('编辑参数失败')
        this.$message.success('编辑参数成功')
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // 编辑对话框的关闭
    editClose(){
      this.$refs.editForm.resetFields()
      this.editDialogVisible = false
    },
    // 删除按钮
    async deleteBtn(params){
      const result = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(result !== 'confirm') return this.$message.info('已取消了删除')
        const {data:res} = await this.$http.delete('categories/' + this.cateId + '/attributes/' + params.attr_id)
        if(res.meta.status !== 200) return this.$message.error('删除删除失败')
        this.$message.success('删除参数成功')
        this.getParamsData()
    },
    // tag文本框添加的事件
    async handleInput(row){
      if(row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 需要发请求，将数据保存到后台
      this.saveAttrData(row)      
    },
    // 将修改的参数数据提交到后台
    async saveAttrData(row){
      const {data:res} = await this.$http.put('categories/' + this.cateId +'/attributes/' + row.attr_id,
      {attr_name: row.attr_name,
       attr_sel: row.attr_sel,
       attr_vals: row.attr_vals.join(' ')})
      //console.log(res);
      if(res.meta.status !== 200) return this.$message.error('添加失败')
      this.$message.success('添加成功')
    },
    // 文本框的展示按钮
    showInput(row){
      row.inputVisible = true
      // 让文本框自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.focus()
      })
    },
    // tag标签的删除
    async tagClose(row,i){
      row.attr_vals.splice(i,1)
      this.saveAttrData(row) 
    },
  }
}
</script>

<style lang="less" scoped>
div /deep/ .el-card{
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  margin-top: 15px;

  .goods_opt{
    margin: 15px 0;
    
    span{
      margin-right: 10px;
    }
  }

  .el-table{
    margin-top: 15px;
  }

  .el-tag{
    margin: 8px
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
    .input-new-tag {
    width: 100px;
    margin: 8px;
    vertical-align: bottom;
  }
}
</style>